<template>
	<view>
		<button @click="openwebsocket">连接</button>
		<view class="">
			扫码结果：{{result}}
		</view>
		<button @click="lighton">开灯</button>
		<button @click="lightoff">关灯</button>
		<button @click="open">连接</button>
		<button @click="openLin">开</button>
	</view>
</template>

<script>
	// const usbPlugin = uni.requireNativePlugin('usb-plugin');
	// var websocket_connected = false;
	let websocketCtrl, websocketData
	// var output;
	export default {
		data() {
			return {
				result: null,
				flag: false,
			}
		},
		methods: {
			openwebsocket() {
				this.vbarOpen("localhost", "2693");
			},
			vbarOpen() {
				if (!this.flag) {
					var host = "ws://localhost:2693";
					websocketCtrl = new WebSocket(host, 'ctrl');
					websocketData = new WebSocket(host, 'data');
					// output = document.getElementById("output");

					websocketData.onopen = function(evt) {
						this.flag = true;
						this.websocketOpenState(evt);
					}


					websocketData.onmessage = function(evt) {
						websocketDecode(evt.data);
					}
				}

				setTimeout(this.vbarOpen(), 3000);
			},
			websocketOpenState(message) {
				uni.showToast({
					title: '已连接' + message,
					icon: 'none',
					duration: 5000
				})
			},
			// 接收
			websocketDecode(message) {
				uni.showToast({
					title: '接收' + message,
					icon: 'none',
					duration: 5000
				})
				this.result = message
			},
			opendev() {

			},
			lighton() {
				websocketCtrl.send("lighton")
			},
			lightoff() {
				websocketCtrl.send("lightoff");
			},
			open() {
				const that = this
				if (!this.flag) {
					var host = "ws://localhost:2693";
					websocketCtrl = uni.connectSocket({
						url: host,
						method: 'GET',
						success(res) {
							// uni.showToast({
							// 	title: '成功 =>' + res,
							// 	icon: 'success',
							// 	duration: 5000
							// })
							uni.onSocketOpen(() => {
								uni.showToast({
									title: '连接打开',
									icon: 'none',
									duration: 5000
								})
								that.receiveSocket()
							})
							uni.onSocketError(() => {
								uni.showToast({
									title: '连接失败',
									icon: 'error',
									duration: 5000
								})
							})
						},
						fail(err) {
							uni.showToast({
								title: '失败 =>' + err,
								icon: 'error',
								duration: 5000
							})
						}
					})
				}
			},
			receiveSocket() {
				uni.onSocketMessage(res => {
					uni.showToast({
						title: '接收 =>' + res,
						icon: 'none',
						duration: 5000
					})
				})
			},
			openLin() {
				uni.sendSocketMessage({
					data: 'lighton'
				})
			},
			linClose() {
				uni.sendSocketMessage({
					data: 'lightoff'
				})
			}
		}
	}
</script>

<style></style>